<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>11-Stream流 | Ywrby个人博客网站</title><meta name="keywords" content="Java"><meta name="author" content="Ywrby"><meta name="copyright" content="Ywrby"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Stream流的概述概念得益于Lambda所带来的函数式编程，用于解决已有集合&#x2F;数组类库有的弊端 用途解决已有集合类库或者数组API的弊端 实例1234567891011121314151617181920212223242526272829package StreamDemo;import java.util.ArrayList;import java.util.List;public clas">
<meta property="og:type" content="article">
<meta property="og:title" content="11-Stream流">
<meta property="og:url" content="http://ywrby.cn/2021/03/03/11-Stream%E6%B5%81/index.html">
<meta property="og:site_name" content="Ywrby个人博客网站">
<meta property="og:description" content="Stream流的概述概念得益于Lambda所带来的函数式编程，用于解决已有集合&#x2F;数组类库有的弊端 用途解决已有集合类库或者数组API的弊端 实例1234567891011121314151617181920212223242526272829package StreamDemo;import java.util.ArrayList;import java.util.List;public clas">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="http://ywrby.cn/img/72124553_p0.jpg">
<meta property="article:published_time" content="2021-03-03T05:59:21.000Z">
<meta property="article:modified_time" content="2021-03-03T07:34:58.000Z">
<meta property="article:author" content="Ywrby">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://ywrby.cn/img/72124553_p0.jpg"><link rel="shortcut icon" href="/img/title.png"><link rel="canonical" href="http://ywrby.cn/2021/03/03/11-Stream%E6%B5%81/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"We didn't find any results for the search: ${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '11-Stream流',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-03-03 15:34:58'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    document.addEventListener('pjax:complete', detectApple)})(window)</script><link rel="stylesheet" href="/css/background.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Ywrby个人博客网站" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/ywrby.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">127</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">22</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Bilibili</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/bangumis/"><i class="fa-fw fas fa-video"></i><span> 追番列表</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://space.bilibili.com/353923033"><i class="fa-fw fas fa-music"></i><span> B站主页</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/72124553_p0.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Ywrby个人博客网站</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> Search</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Bilibili</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/bangumis/"><i class="fa-fw fas fa-video"></i><span> 追番列表</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://space.bilibili.com/353923033"><i class="fa-fw fas fa-music"></i><span> B站主页</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">11-Stream流</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2021-03-03T05:59:21.000Z" title="Created 2021-03-03 13:59:21">2021-03-03</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2021-03-03T07:34:58.000Z" title="Updated 2021-03-03 15:34:58">2021-03-03</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="11-Stream流"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Stream流的概述"><a href="#Stream流的概述" class="headerlink" title="Stream流的概述"></a>Stream流的概述</h1><h3 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h3><p>得益于Lambda所带来的函数式编程，用于解决已有集合/数组类库有的弊端</p>
<h3 id="用途"><a href="#用途" class="headerlink" title="用途"></a>用途</h3><p>解决已有集合类库或者数组API的弊端</p>
<h3 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> StreamDemo;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StreamDemo1</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        List&lt;String&gt; lists = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        lists.add(<span class="string">&quot;Leslie&quot;</span>); lists.add(<span class="string">&quot;Lily&quot;</span>); lists.add(<span class="string">&quot;Leon&quot;</span>);</span><br><span class="line">        lists.add(<span class="string">&quot;John&quot;</span>); lists.add(<span class="string">&quot;Li&quot;</span>); lists.add(<span class="string">&quot;Herge&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//不借助Stream流的情况下筛选出数组中首字母为L，长度大于3的名字</span></span><br><span class="line">        List&lt;String&gt; lists_search=<span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (String s:lists)&#123;</span><br><span class="line">            <span class="keyword">if</span>(s.startsWith(<span class="string">&quot;L&quot;</span>) &amp; s.length()&gt;<span class="number">3</span>)&#123;</span><br><span class="line">                lists_search.add(s);</span><br><span class="line">                System.out.println(s);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;-----------------&quot;</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//使用Stream流筛选,整个代码被简化</span></span><br><span class="line">        lists.stream().filter(s-&gt;s.startsWith(<span class="string">&quot;L&quot;</span>)).filter(s-&gt;s.length()&gt;<span class="number">3</span>)</span><br><span class="line">                .forEach(System.out::println);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Stream流类似一根传送带，集合中的元素在上面可以被操作</p>
<h2 id="Stream流运作思想"><a href="#Stream流运作思想" class="headerlink" title="Stream流运作思想"></a>Stream流运作思想</h2><ol>
<li>首先得到集合或者数组的Stream流(得到一根传送带)</li>
<li>然后用这个Stream流操作集合或者数组的元素</li>
<li>然后用Stream流简化替代集合操作的API</li>
</ol>
<h1 id="Stream流的获取"><a href="#Stream流的获取" class="headerlink" title="Stream流的获取"></a>Stream流的获取</h1><h3 id="集合获取Stream流的API"><a href="#集合获取Stream流的API" class="headerlink" title="集合获取Stream流的API"></a>集合获取Stream流的API</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">default</span> Stream&lt;E&gt; <span class="title">stream</span><span class="params">()</span></span>;</span><br></pre></td></tr></table></figure>

<h2 id="获取方式"><a href="#获取方式" class="headerlink" title="获取方式"></a>获取方式</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> StreamDemo;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Array;</span><br><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line"><span class="keyword">import</span> java.util.stream.Stream;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StreamDemo2</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//Collection集合获取Stream流</span></span><br><span class="line">        Collection&lt;String&gt; c = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        Stream&lt;String&gt; s1 = c.stream();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//Map集合获取Stream流</span></span><br><span class="line">        Map&lt;String, Integer&gt; m = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">        <span class="comment">//获取Map集合的键的Stream流</span></span><br><span class="line">        Stream&lt;String&gt; s2 = m.keySet().stream();</span><br><span class="line">        <span class="comment">//获取Map集合的值的Stream流</span></span><br><span class="line">        Stream&lt;Integer&gt; s3 = m.values().stream();</span><br><span class="line">        <span class="comment">//将键和值转换为set有序对类型，从而看作一个整体，获取键值对的Stream流</span></span><br><span class="line">        Stream&lt;Map.Entry&lt;String, Integer&gt;&gt; s4 = m.entrySet().stream();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//数组获取Stream流,两种获取方式</span></span><br><span class="line">        String[] arrs=<span class="keyword">new</span> String[]&#123;<span class="string">&quot;Leslie&quot;</span>,<span class="string">&quot;Lily&quot;</span>&#125;;</span><br><span class="line">        Stream&lt;String&gt; s5= Arrays.stream(arrs);</span><br><span class="line">        Stream&lt;String&gt; s6=Stream.of(arrs);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到集合获取Stream流，普遍采用stream()方法，数组获取Stream流有两种方式Arrays.stream(数组)/Stream.of(数组)</p>
<h3 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> StreamDemo;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> java.util.function.Predicate;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StreamDemo3</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        List&lt;String&gt; lists = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        lists.add(<span class="string">&quot;Leslie&quot;</span>); lists.add(<span class="string">&quot;Lily&quot;</span>); lists.add(<span class="string">&quot;Leon&quot;</span>);</span><br><span class="line">        lists.add(<span class="string">&quot;John&quot;</span>); lists.add(<span class="string">&quot;Li&quot;</span>); lists.add(<span class="string">&quot;Herge&quot;</span>);</span><br><span class="line"></span><br><span class="line">        List&lt;String&gt; lists_search=<span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        </span><br><span class="line">        </span><br><span class="line">        <span class="comment">/* </span></span><br><span class="line"><span class="comment">         * 通过filter的匿名内部类写法可以看出，filter是通过</span></span><br><span class="line"><span class="comment">         * 新建一个Predicate来指定条件，筛选数组/集合中的元素</span></span><br><span class="line"><span class="comment">         * 而这个筛选规则就是Predicate类中的test方法</span></span><br><span class="line"><span class="comment">         * 它会通过返回布尔值决定该元素是否删除</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        lists.stream().filter(<span class="keyword">new</span> Predicate&lt;String&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">test</span><span class="params">(String s)</span> </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> s.length()&gt;<span class="number">3</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).filter(<span class="keyword">new</span> Predicate&lt;String&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">test</span><span class="params">(String s)</span> </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> s.startsWith(<span class="string">&quot;L&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).forEach(s -&gt; System.out.println(s));</span><br><span class="line"></span><br><span class="line">        </span><br><span class="line">        <span class="comment">//是因为Predicate是一个函数式接口，所以才可以利用Lambda表达式简化</span></span><br><span class="line">        lists.stream().filter(s-&gt;s.startsWith(<span class="string">&quot;L&quot;</span>)).filter(s-&gt;s.length()&gt;<span class="number">3</span>)</span><br><span class="line">                .forEach(System.out::println);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="Stream流常用API"><a href="#Stream流常用API" class="headerlink" title="Stream流常用API"></a>Stream流常用API</h1><h4 id="forEach"><a href="#forEach" class="headerlink" title="forEach"></a>forEach</h4><p>遍历集合元素</p>
<h4 id="count"><a href="#count" class="headerlink" title="count"></a>count</h4><p>统计个数(返回值类型为long)</p>
<h4 id="filter"><a href="#filter" class="headerlink" title="filter"></a>filter</h4><p>过滤元素</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">Stream&lt;T&gt; <span class="title">filter</span><span class="params">(Predicate&lt;? <span class="keyword">super</span> T&gt; predicate)</span></span>;</span><br></pre></td></tr></table></figure>

<h4 id="limit"><a href="#limit" class="headerlink" title="limit"></a>limit</h4><p>取符合条件的前几个元素</p>
<h4 id="skip"><a href="#skip" class="headerlink" title="skip"></a>skip</h4><p>跳出符合条件的前几个元素</p>
<h2 id="Stream流的加工方法map"><a href="#Stream流的加工方法map" class="headerlink" title="Stream流的加工方法map"></a>Stream流的加工方法map</h2><p>map (映射)，指把原来的元素经过加工之后，重新放回去</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> StreamDemo;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.atomic.AtomicInteger;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StreamDemo4</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        List&lt;String&gt; lists = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        lists.add(<span class="string">&quot;Leslie&quot;</span>); lists.add(<span class="string">&quot;Lily&quot;</span>); lists.add(<span class="string">&quot;Leon&quot;</span>);</span><br><span class="line">        lists.add(<span class="string">&quot;John&quot;</span>); lists.add(<span class="string">&quot;Li&quot;</span>); lists.add(<span class="string">&quot;Herge&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//给所有名字后面都加上序号</span></span><br><span class="line">        AtomicInteger i= <span class="keyword">new</span> AtomicInteger(<span class="number">1</span>);</span><br><span class="line">        lists.stream().map(s -&gt; s+(i.getAndIncrement())).forEach(System.out::println);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="运行结果"><a href="#运行结果" class="headerlink" title="运行结果"></a>运行结果</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Leslie1</span><br><span class="line">Lily2</span><br><span class="line">Leon3</span><br><span class="line">John4</span><br><span class="line">Li5</span><br><span class="line">Herge6</span><br></pre></td></tr></table></figure>

<h4 id="还可以将其转换为对象再放回其中"><a href="#还可以将其转换为对象再放回其中" class="headerlink" title="还可以将其转换为对象再放回其中"></a>还可以将其转换为对象再放回其中</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> StreamDemo;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.atomic.AtomicInteger;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StreamDemo4</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        List&lt;String&gt; lists = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        lists.add(<span class="string">&quot;Leslie&quot;</span>); lists.add(<span class="string">&quot;Lily&quot;</span>); lists.add(<span class="string">&quot;Leon&quot;</span>);</span><br><span class="line">        lists.add(<span class="string">&quot;John&quot;</span>); lists.add(<span class="string">&quot;Li&quot;</span>); lists.add(<span class="string">&quot;Herge&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//给所有名字后面都加上序号</span></span><br><span class="line">        <span class="comment">//AtomicInteger i= new AtomicInteger(1);</span></span><br><span class="line">        <span class="comment">//lists.stream().map(s -&gt; s+(i.getAndIncrement())).forEach(System.out::println);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//将所有名字转换为学生对象再放回去</span></span><br><span class="line">        lists.stream().map(Student::<span class="keyword">new</span>).forEach(System.out::println);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Student</span></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> age;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> score;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Student</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Student</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="Stream流的合并方法concat"><a href="#Stream流的合并方法concat" class="headerlink" title="Stream流的合并方法concat"></a>Stream流的合并方法concat</h2><p><strong>注意concat方法只能同时合并两个流</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> StreamDemo;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.atomic.AtomicInteger;</span><br><span class="line"><span class="keyword">import</span> java.util.stream.Stream;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StreamDemo5</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        List&lt;String&gt; lists = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        lists.add(<span class="string">&quot;Leslie&quot;</span>); lists.add(<span class="string">&quot;Lily&quot;</span>); lists.add(<span class="string">&quot;Leon&quot;</span>);</span><br><span class="line">        lists.add(<span class="string">&quot;John&quot;</span>); lists.add(<span class="string">&quot;Li&quot;</span>); lists.add(<span class="string">&quot;Herge&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//合并相同的Stream流</span></span><br><span class="line">        Stream&lt;String&gt; s1=lists.stream();</span><br><span class="line">        Stream&lt;String&gt; s2=Stream.of(<span class="string">&quot;Happy&quot;</span>,<span class="string">&quot;Sad&quot;</span>,<span class="string">&quot;Shy&quot;</span>);</span><br><span class="line">        <span class="comment">//直接调用concat并按照类型创建新的Stream流即可</span></span><br><span class="line">        Stream&lt;String&gt; s3=Stream.concat(s1,s2);</span><br><span class="line">        <span class="comment">//合并不同类型的s1,s4两条Stream流</span></span><br><span class="line">        Stream&lt;String&gt; s4=lists.stream();</span><br><span class="line">        Stream&lt;Integer&gt; s5=Stream.of(<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>,<span class="number">40</span>);</span><br><span class="line">        <span class="comment">//可行方法之一，就是直接定义对象类型的Stream流</span></span><br><span class="line">        Stream&lt;Object&gt; s6=Stream.concat(s4,s5);</span><br><span class="line"></span><br><span class="line">        s3.forEach(System.out::println);</span><br><span class="line">        System.out.println(<span class="string">&quot;------------&quot;</span>);</span><br><span class="line">        s6.forEach(System.out::println);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="运行结果-1"><a href="#运行结果-1" class="headerlink" title="运行结果"></a>运行结果</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">Leslie</span><br><span class="line">Lily</span><br><span class="line">Leon</span><br><span class="line">John</span><br><span class="line">Li</span><br><span class="line">Herge</span><br><span class="line">Happy</span><br><span class="line">Sad</span><br><span class="line">Shy</span><br><span class="line">------------</span><br><span class="line">Leslie</span><br><span class="line">Lily</span><br><span class="line">Leon</span><br><span class="line">John</span><br><span class="line">Li</span><br><span class="line">Herge</span><br><span class="line"><span class="number">10</span></span><br><span class="line"><span class="number">20</span></span><br><span class="line"><span class="number">30</span></span><br><span class="line"><span class="number">40</span></span><br></pre></td></tr></table></figure>

<h2 id="Stream终结与非终结方法"><a href="#Stream终结与非终结方法" class="headerlink" title="Stream终结与非终结方法"></a>Stream终结与非终结方法</h2><h3 id="终结方法"><a href="#终结方法" class="headerlink" title="终结方法"></a>终结方法</h3><p>一旦Stream流调用终结方法，流的操作就全部终结了，<strong>不能继续使用，只能创建新的Stream操作</strong>，其原因一般是没有返回值，或返回值不是Stream流对象</p>
<h4 id="终结方法包括forEach-count等等"><a href="#终结方法包括forEach-count等等" class="headerlink" title="终结方法包括forEach(),count等等"></a>终结方法包括forEach(),count等等</h4><h3 id="非终结方法"><a href="#非终结方法" class="headerlink" title="非终结方法"></a>非终结方法</h3><p>每次调用完成以后都会<strong>返回一个新的流对象</strong>，可以继续使用，支持链式编程</p>
<h4 id="非终结方法包括filter-skip-limit-map-concat等等"><a href="#非终结方法包括filter-skip-limit-map-concat等等" class="headerlink" title="非终结方法包括filter,skip,limit,map,concat等等"></a>非终结方法包括filter,skip,limit,map,concat等等</h4><h2 id="收集Stream流"><a href="#收集Stream流" class="headerlink" title="收集Stream流"></a>收集Stream流</h2><p>将Stream流的数据转回成集合</p>
<p>Stream流的作用在于将集合转换为一根高效的传送带，再利用Stream流的强大功能对Stream流进行操作。但是实际开发中最终数据的形式应该仍然是集合，所以这就涉及到Stream流的收集</p>
<p>换言之，Stream流只是一种手段，是我们操作数据的一种方式，集合才是我们需要始终用来保存，传输数据的数据结构，也就是目的</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> StreamDemo;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> java.util.Set;</span><br><span class="line"><span class="keyword">import</span> java.util.stream.Collectors;</span><br><span class="line"><span class="keyword">import</span> java.util.stream.Stream;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StreamDemo5</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        List&lt;String&gt; lists = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        lists.add(<span class="string">&quot;Leslie&quot;</span>); lists.add(<span class="string">&quot;Lily&quot;</span>); lists.add(<span class="string">&quot;Leon&quot;</span>);</span><br><span class="line">        lists.add(<span class="string">&quot;John&quot;</span>); lists.add(<span class="string">&quot;Li&quot;</span>); lists.add(<span class="string">&quot;Herge&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//先转换成Stream流并进行筛选</span></span><br><span class="line">        Stream&lt;String&gt; s1=lists.stream().filter(s -&gt; s.length()&gt;=<span class="number">3</span>);</span><br><span class="line">        <span class="comment">//然后进行Stream流的收集，将它们转换为可以用来保存，传输的数据结构</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//转换到set集合</span></span><br><span class="line">        Set&lt;String&gt; set1=s1.collect(Collectors.toSet());</span><br><span class="line">        System.out.println(set1);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//转换到list集合</span></span><br><span class="line">        Stream&lt;String&gt; s2=lists.stream().filter(s -&gt; s.length()&gt;=<span class="number">3</span>);</span><br><span class="line">        List&lt;String&gt; list1=s2.collect(Collectors.toList());</span><br><span class="line">        System.out.println(list1);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//转换到数组</span></span><br><span class="line">        Stream&lt;String&gt; s3=lists.stream().filter(s -&gt; s.length()&gt;=<span class="number">3</span>);</span><br><span class="line">        Stream&lt;String&gt; s4=lists.stream().filter(s -&gt; s.length()&gt;=<span class="number">3</span>);</span><br><span class="line">        <span class="comment">//两种转换方式，（还可以强转）</span></span><br><span class="line">        Object[] arrs1=s3.toArray();</span><br><span class="line">        <span class="comment">//接用构造器引用申明转换成的数组类型</span></span><br><span class="line">        String[] arrs2=s4.toArray(String[]::<span class="keyword">new</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="mailto:undefined">Ywrby</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="http://ywrby.cn/2021/03/03/11-Stream%E6%B5%81/">http://ywrby.cn/2021/03/03/11-Stream%E6%B5%81/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/">Java</a></div><div class="post_share"><div class="social-share" data-image="/img/72124553_p0.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/03/03/12-File%E7%B1%BB/"><img class="prev-cover" src="/img/68304874_p0.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">12-File类</div></div></a></div><div class="next-post pull-right"><a href="/2021/03/03/10-%E6%96%B9%E6%B3%95%E5%BC%95%E7%94%A8/"><img class="next-cover" src="/img/72175872_p0.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">10-方法引用</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>Related Articles</span></div><div class="relatedPosts-list"><div><a href="/2021/07/27/1-JVM%E5%9F%BA%E7%A1%80/" title="1-JVM基础"><img class="cover" src="/img/illust_3518827_20191113_165540.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-07-27</div><div class="title">1-JVM基础</div></div></a></div><div><a href="/2021/03/03/1-%E5%BC%82%E5%B8%B8/" title="1-异常"><img class="cover" src="/img/72124553_p0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-03</div><div class="title">1-异常</div></div></a></div><div><a href="/2021/03/03/10-%E6%96%B9%E6%B3%95%E5%BC%95%E7%94%A8/" title="10-方法引用"><img class="cover" src="/img/72175872_p0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-03</div><div class="title">10-方法引用</div></div></a></div><div><a href="/2021/03/03/12-File%E7%B1%BB/" title="12-File类"><img class="cover" src="/img/68304874_p0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-03</div><div class="title">12-File类</div></div></a></div><div><a href="/2021/03/03/13-%E9%80%92%E5%BD%92/" title="13-递归"><img class="cover" src="/img/83821828_p0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-03</div><div class="title">13-递归</div></div></a></div><div><a href="/2021/03/03/15-%E5%88%9D%E5%A7%8B%E5%8C%96%E5%92%8C%E6%B8%85%E7%90%86/" title="15-初始化和清理"><img class="cover" src="/img/68304874_p0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-03</div><div class="title">15-初始化和清理</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> Comment</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/ywrby.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Ywrby</div><div class="author-info__description">Students majoring in CS at SWU</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">127</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">22</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/ywrby"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="mailto:ywrby0214@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="https://space.bilibili.com/353923033" target="_blank" title="Bilibili"><i class="fas fa-file-video"></i></a><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2278431384&amp;site=qq&amp;menu=yes" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="https://twitter.com/ywrby1" target="_blank" title="Twitter"><i class="fab fa-twitter"></i></a><a class="social-icon" href="https://www.facebook.com/profile.php?id=100033741068822" target="_blank" title="Facebook"><i class="fab fa-facebook"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>Announcement</span></div><div class="announcement_content">Less is more</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Stream%E6%B5%81%E7%9A%84%E6%A6%82%E8%BF%B0"><span class="toc-number">1.</span> <span class="toc-text">Stream流的概述</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A6%82%E5%BF%B5"><span class="toc-number">1.0.1.</span> <span class="toc-text">概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%A8%E9%80%94"><span class="toc-number">1.0.2.</span> <span class="toc-text">用途</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9E%E4%BE%8B"><span class="toc-number">1.0.3.</span> <span class="toc-text">实例</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Stream%E6%B5%81%E8%BF%90%E4%BD%9C%E6%80%9D%E6%83%B3"><span class="toc-number">1.1.</span> <span class="toc-text">Stream流运作思想</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Stream%E6%B5%81%E7%9A%84%E8%8E%B7%E5%8F%96"><span class="toc-number">2.</span> <span class="toc-text">Stream流的获取</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9B%86%E5%90%88%E8%8E%B7%E5%8F%96Stream%E6%B5%81%E7%9A%84API"><span class="toc-number">2.0.1.</span> <span class="toc-text">集合获取Stream流的API</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96%E6%96%B9%E5%BC%8F"><span class="toc-number">2.1.</span> <span class="toc-text">获取方式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8E%9F%E7%90%86"><span class="toc-number">2.1.1.</span> <span class="toc-text">原理</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Stream%E6%B5%81%E5%B8%B8%E7%94%A8API"><span class="toc-number">3.</span> <span class="toc-text">Stream流常用API</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#forEach"><span class="toc-number">3.0.0.1.</span> <span class="toc-text">forEach</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#count"><span class="toc-number">3.0.0.2.</span> <span class="toc-text">count</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#filter"><span class="toc-number">3.0.0.3.</span> <span class="toc-text">filter</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#limit"><span class="toc-number">3.0.0.4.</span> <span class="toc-text">limit</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#skip"><span class="toc-number">3.0.0.5.</span> <span class="toc-text">skip</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Stream%E6%B5%81%E7%9A%84%E5%8A%A0%E5%B7%A5%E6%96%B9%E6%B3%95map"><span class="toc-number">3.1.</span> <span class="toc-text">Stream流的加工方法map</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C"><span class="toc-number">3.1.0.1.</span> <span class="toc-text">运行结果</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%BF%98%E5%8F%AF%E4%BB%A5%E5%B0%86%E5%85%B6%E8%BD%AC%E6%8D%A2%E4%B8%BA%E5%AF%B9%E8%B1%A1%E5%86%8D%E6%94%BE%E5%9B%9E%E5%85%B6%E4%B8%AD"><span class="toc-number">3.1.0.2.</span> <span class="toc-text">还可以将其转换为对象再放回其中</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Stream%E6%B5%81%E7%9A%84%E5%90%88%E5%B9%B6%E6%96%B9%E6%B3%95concat"><span class="toc-number">3.2.</span> <span class="toc-text">Stream流的合并方法concat</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C-1"><span class="toc-number">3.2.0.1.</span> <span class="toc-text">运行结果</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Stream%E7%BB%88%E7%BB%93%E4%B8%8E%E9%9D%9E%E7%BB%88%E7%BB%93%E6%96%B9%E6%B3%95"><span class="toc-number">3.3.</span> <span class="toc-text">Stream终结与非终结方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BB%88%E7%BB%93%E6%96%B9%E6%B3%95"><span class="toc-number">3.3.1.</span> <span class="toc-text">终结方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BB%88%E7%BB%93%E6%96%B9%E6%B3%95%E5%8C%85%E6%8B%ACforEach-count%E7%AD%89%E7%AD%89"><span class="toc-number">3.3.1.1.</span> <span class="toc-text">终结方法包括forEach(),count等等</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9D%9E%E7%BB%88%E7%BB%93%E6%96%B9%E6%B3%95"><span class="toc-number">3.3.2.</span> <span class="toc-text">非终结方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%9D%9E%E7%BB%88%E7%BB%93%E6%96%B9%E6%B3%95%E5%8C%85%E6%8B%ACfilter-skip-limit-map-concat%E7%AD%89%E7%AD%89"><span class="toc-number">3.3.2.1.</span> <span class="toc-text">非终结方法包括filter,skip,limit,map,concat等等</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%94%B6%E9%9B%86Stream%E6%B5%81"><span class="toc-number">3.4.</span> <span class="toc-text">收集Stream流</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/12/25/22-%E5%86%85%E5%AD%98%E7%A9%BA%E9%97%B4%E6%89%A9%E5%85%85%EF%BC%88%E8%A6%86%E7%9B%96%E4%B8%8E%E4%BA%A4%E6%8D%A2%EF%BC%89/" title="22-内存空间扩充（覆盖与交换）"><img src="/img/67888138_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="22-内存空间扩充（覆盖与交换）"/></a><div class="content"><a class="title" href="/2021/12/25/22-%E5%86%85%E5%AD%98%E7%A9%BA%E9%97%B4%E6%89%A9%E5%85%85%EF%BC%88%E8%A6%86%E7%9B%96%E4%B8%8E%E4%BA%A4%E6%8D%A2%EF%BC%89/" title="22-内存空间扩充（覆盖与交换）">22-内存空间扩充（覆盖与交换）</a><time datetime="2021-12-25T08:15:49.000Z" title="Created 2021-12-25 16:15:49">2021-12-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/12/19/21-%E5%86%85%E5%AD%98%E4%B8%8E%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/" title="21-内存与内存管理"><img src="/img/80857290_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="21-内存与内存管理"/></a><div class="content"><a class="title" href="/2021/12/19/21-%E5%86%85%E5%AD%98%E4%B8%8E%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/" title="21-内存与内存管理">21-内存与内存管理</a><time datetime="2021-12-19T09:57:53.000Z" title="Created 2021-12-19 17:57:53">2021-12-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/12/11/20-%E6%AD%BB%E9%94%81/" title="20-死锁"><img src="/img/81934649_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="20-死锁"/></a><div class="content"><a class="title" href="/2021/12/11/20-%E6%AD%BB%E9%94%81/" title="20-死锁">20-死锁</a><time datetime="2021-12-11T06:20:20.000Z" title="Created 2021-12-11 14:20:20">2021-12-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/11/28/19-%E7%AE%A1%E7%A8%8B/" title="19-管程"><img src="/img/72581222_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="19-管程"/></a><div class="content"><a class="title" href="/2021/11/28/19-%E7%AE%A1%E7%A8%8B/" title="19-管程">19-管程</a><time datetime="2021-11-28T08:39:08.000Z" title="Created 2021-11-28 16:39:08">2021-11-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/11/17/18-%E4%BF%A1%E5%8F%B7%E9%87%8F%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%EF%BC%88%E5%90%B8%E7%83%9F%E8%80%85%EF%BC%8C%E8%AF%BB%E8%80%85-%E5%86%99%E8%80%85%E7%AD%89%EF%BC%89/" title="18-信号量相关问题（吸烟者，读者-写者等）"><img src="/img/73604608_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="18-信号量相关问题（吸烟者，读者-写者等）"/></a><div class="content"><a class="title" href="/2021/11/17/18-%E4%BF%A1%E5%8F%B7%E9%87%8F%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%EF%BC%88%E5%90%B8%E7%83%9F%E8%80%85%EF%BC%8C%E8%AF%BB%E8%80%85-%E5%86%99%E8%80%85%E7%AD%89%EF%BC%89/" title="18-信号量相关问题（吸烟者，读者-写者等）">18-信号量相关问题（吸烟者，读者-写者等）</a><time datetime="2021-11-17T12:08:38.000Z" title="Created 2021-11-17 20:08:38">2021-11-17</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/img/72124553_p0.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By Ywrby</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="Scroll To Comments"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="Back To Top"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">Local search</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="Search for Posts" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/katex@latest/dist/katex.min.css"><script src="https://cdn.jsdelivr.net/npm/katex-copytex@latest/dist/katex-copytex.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/katex-copytex@latest/dist/katex-copytex.min.css"><script>(() => {
  document.querySelectorAll('#article-container span.katex-display').forEach(item => {
    btf.wrap(item, 'div', { class: 'katex-wrap'})
  })
})()</script><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'QkExI1n70lz2qs7pVpmFeKqp-gzGzoHsz',
      appKey: 'WhG61iDj96bflhu6CIpmE9V8',
      placeholder: 'Please leave your footprints',
      avatar: 'mp',
      meta: 'nick,mail,link'.split(','),
      pageSize: '10',
      lang: 'zh-CN',
      recordIP: false,
      serverURLs: '',
      emojiCDN: '',
      emojiMaps: "",
      enableQQ: false,
      path: window.location.pathname,
      requiredFields: ["nick,mail"],
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><div class="aplayer no-destroy" data-id="5402995011" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-lrctype=0	data-order="random" data-preload="none" data-autoplay="true" muted></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>